package com.mxy.myapplication.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.BitmapEncoder;
import com.mxy.myapplication.R;
import com.mxy.myapplication.activity.MainActivity;
import com.mxy.myapplication.pojo.Pojo1;
import com.mxy.myapplication.util.Util;

import java.util.ArrayList;

/**
 * 带阻尼效果的RecyclerView适配器
 */

public class AdapterForRecyclerView_Snap extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  private ArrayList<Pojo1> data;
  private LayoutInflater lf;
  private Context context;


  public AdapterForRecyclerView_Snap(Context context, ArrayList<Pojo1> data) {
    this.data = data;
    this.lf = LayoutInflater.from(context);
    this.context = context;
  }


  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new MyViewHolder(lf.inflate(R.layout.item_recyclerview_snap, null, false));
  }

  @Override
  public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    MyViewHolder myViewHolder = (MyViewHolder) holder;

    myViewHolder.imageView.setOnClickListener(new OnItemClickListener(position));
    Glide.with(context)
            .load(data.get(position).drawableID)
            .asBitmap()
            .encoder(new BitmapEncoder(Bitmap.CompressFormat.PNG, 100))
            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .dontAnimate()
            .animate(R.anim.alpha)
            .into(myViewHolder.imageView);

  }

  @Override
  public int getItemCount() {
    return data.size();
  }

  private class MyViewHolder extends RecyclerView.ViewHolder {

    private ImageView imageView;

    private MyViewHolder(View itemView) {
      super(itemView);
      imageView = (ImageView) itemView.findViewById(R.id.imageview);
    }
  }

  private class OnItemClickListener implements View.OnClickListener {

    private int position;

    private OnItemClickListener(int position) {
      this.position = position;
    }

    @Override
    public void onClick(View v) {
      Util.showToast(context, String.valueOf(position));
      if (AdapterForRecyclerView_Snap.this.context instanceof MainActivity) {
        Intent intent = new Intent("com.mxy.myapplication.activity.DownLoadScheduleActivity.class");
        MainActivity mainActivity = (MainActivity) AdapterForRecyclerView_Snap.this.context;
        Util.startActivityByAction(mainActivity, intent);
      }
    }
  }
}